<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Javascript的闭包</h1>

<script>
    //1.外部函数读取其他函数内部变量的函数
    /*
    function fn(){
        var num = 100;
        function test(){
            return num;
        }
        return test;
    }

    function haha(){
        let f = fn();
        let n = f();
        console.log(n); //haha函数获取到fn函数内的局部变量。
    }
    haha();*/

    //2.让某些局部变量的值始终保持在内存中
    /*
    function fn(){
        var num = 100;
        increasement = function(){
            num++;
        };
        function test(){
            console.log(num);
            return num;
        }
        return test;
    }

    var f = fn();
    f();
    increasement();
    f();*/


    //3.返回匿名函数的闭包
    /*
    function fn(){
        var num = 100;
        increasement = function(){
            num++;
        };
        return function (){
            console.log(num);
            return num;
        }
    }

    var f = fn();
    f();
    increasement();
    f();*/

    //4.如果f一旦重新赋值，那么那些始终保持在内存中变量的值，也将被重新初始化
    function fn(){
        var num = 100;
        increasement = function(){
            num++;
        };
        return function (){
            console.log(num);
            return num;
        }
    }

    var f = fn();
    f();
    increasement();
    f = fn(); //f被重新赋值
    f();



</script>
</body>
</html>